import React, { Component } from 'react';
import { Form, Row, Col, Checkbox, Button, message } from 'antd';
import Link from 'umi/link';
import { phone as phoneReg } from '@/utils/regexp';
import SparkMD5 from 'spark-md5';
import withRedirect from '@/utils/withRedirect';
import withRouter from 'umi/withRouter';
import { connect } from 'dva';
import { setToken, getAccount, setAccount, removeAccount } from '@/utils/cookies';
import LoginWrapper from '@/components/LoginWrapper';

const FormItem = Form.Item;
const { AccountFormItem, GetYCodeFormItem, PasswordFormItem } = LoginWrapper;

@connect(({ loading: { models: { login } } }) => ({
  loading: !!login,
}))
@Form.create()
@withRouter
class LoginForm extends Component {
  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form, loginType } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (!err) {
        // 登陆类型 1手机号登陆 2邮箱账号登陆 ,
        // values.loginType = loginType === 'pwd' ? 2 : 1;
        let values = {
          ...fieldsValue,
        };
        let type = 'login/loginWithPwd';
        if (loginType === 'pwd') {
          values.password = SparkMD5.hash(values.password);
        }
        if (loginType === 'msg') {
          type = 'login/loginWithSms';
        }
        dispatch({
          type,
          payload: values,
        })
          .then(({ token }) => {
            setToken(token);
            message.success('登录成功');
            window.location.href = '/home/#/dashboard';
          })
          .catch(errMsg => {
            message.error(errMsg);
          });

        if (values.remember) {
          setAccount(values.username);
        } else {
          removeAccount();
        }
      }
    });
  };

  render() {
    const {
      form,
      form: { getFieldDecorator },
      userType,
      loginType,
      loading,
    } = this.props;
    const initialAccount = getAccount();
    const accountRules =
      loginType === 'msg'
        ? {
            rules: [
              {
                required: true,
                message: '请输入正确的手机号',
                pattern: phoneReg,
              },
            ],
            placeholder: '请输入手机号',
          }
        : {};
    return (
      <div className="form-wrapper">
        <div className="tabs">
          <Link
            to={withRedirect(
              `/login?userType=${userType}&loginType=${loginType === 'pwd' ? 'msg' : 'pwd'}`
            )}
            className={loginType === 'pwd' ? 'active' : ''}
          >
            账号密码登录
          </Link>
          <Link
            to={withRedirect(
              `/login?userType=${userType}&loginType=${loginType === 'pwd' ? 'msg' : 'pwd'}`
            )}
            className={loginType === 'msg' ? 'active' : ''}
          >
            手机号登录
          </Link>
        </div>
        <Form onSubmit={this.handleSubmit}>
          <AccountFormItem
            form={form}
            disabled={loading}
            focus
            id="username"
            initialValue={initialAccount}
            {...accountRules}
          />
          {loginType === 'pwd' && (
            <PasswordFormItem disabled={loading} focus={!!initialAccount} form={form} />
          )}
          {loginType === 'msg' && (
            <GetYCodeFormItem
              disabled={loading}
              id="code"
              validField="username"
              type="phone"
              serviceType={1}
              focus={!!initialAccount}
              form={form}
            />
          )}
          <Row>
            <Col span={12} className="tl">
              <FormItem>
                {getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: !!initialAccount,
                })(<Checkbox disabled={loading}>记住帐号</Checkbox>)}
              </FormItem>
            </Col>
            <Col span={12} className="tr">
              <FormItem>
                <Link to="/resetPassword">
                  <span className="link">忘记密码</span>
                </Link>
              </FormItem>
            </Col>
          </Row>
          <div className="tc">
            <Button
              className="primary-button"
              disabled={loading}
              htmlType="submit"
              loading={loading}
            >
              {loading ? '请稍候' : '登录'}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}
export default LoginForm;
